package com.project.controller;

import com.alibaba.fastjson2.JSON;
import com.project.bean.MtTicketBean;
import com.project.bean.TicketBean;
import com.project.bean.UserBean;
import com.project.config.RabbitConfig;
import com.project.service.CinemaService;
import com.project.service.IMtTicketService;
import com.project.service.IUserService;
import com.project.util.CreateToken;
import com.project.util.MD5Encryptor;
import com.project.vo.ResultVO;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {


    @Autowired
    private IUserService userService;
    @Autowired
    private IMtTicketService mtTicketService;


    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @GetMapping("login")
    public ResultVO login(String username, String password, HttpServletRequest request) throws NoSuchAlgorithmException {
        UserBean user=userService.login(username, MD5Encryptor.encrypt(password));
        ResultVO resultVO =new ResultVO();
        if (user!=null){
            request.getSession().setAttribute("loginUser",user);
            //把对象转换为json
            String json = JSON.toJSONString(user);
            //生成Token
            String token = CreateToken.createToken(json);
            resultVO.setTag(0);
            resultVO.setJson(token);
        }else {
            resultVO.setTag(1);
            resultVO.setJson("");
        }
        return resultVO;
    }

    /**
     * 购买电影票下单
     * @param mtTicketId
     * @param request
     * @return
     */
    @GetMapping("purchase")
        public String purchase(Integer mtTicketId,HttpServletRequest request) throws InterruptedException {
//        System.out.println("购买");
        //得到当前登录用户
        UserBean user= (UserBean) request.getSession().getAttribute("loginUser");
        mtTicketService.updateNumber(mtTicketId);//电影票数量减1;
        userService.purchase(user.getUserName(), mtTicketId);//添加订单到订单表




        return "ok";
    }
}
